package it.antonio.ilpizze.swing.event;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import javax.swing.SwingUtilities;


public class EventDispatcher {
	private EventMap applicationEventsMap;

	public EventDispatcher(EventMap applicationEventsMap) {
		super();
		this.applicationEventsMap = applicationEventsMap;
	}

	public void publishEDT(final String eventName, final Object... events){
		if (SwingUtilities.isEventDispatchThread()) {
			publish(eventName,events);
		} else {
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					publish(eventName,events);
				}
			});
		}
	}
	
	public void publishAsynchronous(final String eventName, final Object... events){
		ExecutorService service = Executors.newCachedThreadPool(new DaemonThreadFactory());	
		service.execute(new Runnable() {
			
			@Override
			public void run() {
				publish(eventName, events);
				
			}
		});
	}
	
	
	public void publish(String eventName, Object... events){
		applicationEventsMap.throwEvent(eventName, events);
	}
	
	
	private class DaemonThreadFactory implements ThreadFactory{

		private final ThreadFactory delegate = Executors.defaultThreadFactory();
        
		@Override
        public Thread newThread(Runnable r) {
                Thread t = delegate.newThread(r);
                t.setDaemon(true);
                return t;
        }
		
	}
	
	
}
